package com.cskaoyan.gateway.controller.user;

import com.alibaba.fastjson.JSON;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.LoginService;

import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import com.mall.user.intercepter.TokenIntercepter;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestController
public class UserLoginController {

    @Reference(timeout = 3000,check = false)
    LoginService loginService;
    @Reference
    IKaptchaService kaptchaService;

    //验证是否登录
    @GetMapping("user/login")
    public ResponseData userLogin(HttpServletRequest request){
        // 从cookie里面去取token
        String token = (String) request.getAttribute(TokenIntercepter.USER_INFO_KEY);
        log.info("checkLogin token  responseData: " + token);
        Object user = JSON.parse(token);

        return new ResponseUtil<>().setData(user);
    }
    //登录
    @Anoymous
    @PostMapping("user/login")
    public ResponseData login(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request, HttpServletResponse response){
        //先判断验证码是否正确
        String captcha = userLoginRequest.getCaptcha();
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        KaptchaCodeRequest codeRequest = new KaptchaCodeRequest();
        codeRequest.setUuid(uuid);
        codeRequest.setCode(captcha);
        //用validateKaptchaCode来验证，然后判断返回信息是否和设定的成功一样
        KaptchaCodeResponse res = kaptchaService.validateKaptchaCode(codeRequest);
        String responseCode = res.getCode();
        // String successCode = SysRetCodeConstants.SUCCESS.getCode();
        //不一样的话就返回验证码失败的信息
        if (!responseCode.equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil<>().setErrorMsg("验证码不正确");
        }
        //先查询是否激活
        UserLoginResponse userLoginResponse = loginService.login(userLoginRequest);
        if (!SysRetCodeConstants.SUCCESS.getCode().equals(userLoginResponse.getCode())) {
            return new ResponseUtil<>().setErrorMsg(userLoginResponse.getMsg());
        }
        // 将token作为cookie写回到浏览器
        addCookie(response, userLoginResponse);

        return new ResponseUtil<>().setData(userLoginResponse);
    }
    //Cookie
    private void addCookie(HttpServletResponse response, UserLoginResponse userLoginResponse) {
        // # issue1 在这里写回cookie 的时候用的是
        // CookieUtil.genCookieWithDomain(TokenIntercepter.ACCESS_TOKEN, login.getToken(), 60 * 60 * 24, hostAddress)
        Cookie tokenCookie = CookieUtil.genCookie(TokenIntercepter.ACCESS_TOKEN, userLoginResponse.getToken(), "/",60 * 60 * 24);
        log.info("cookie domain is " + tokenCookie.getDomain());
        response.addCookie(tokenCookie);
    }

    //登出
    @RequestMapping("user/loginOut")
    public ResponseData userLoginOut(HttpServletRequest request,HttpServletResponse response){
        deleteCookie(request,response);
        return new ResponseUtil<>().setData(null);
    }
    //删除浏览器中的cookie
    private void deleteCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(TokenIntercepter.ACCESS_TOKEN)){
                    cookie.setValue(null);
                    cookie.setMaxAge(0);// 立即销毁cookie
                    cookie.setPath("/");
                    log.info("deleted cookie domain is: " + cookie.getDomain());
                    //覆盖原来的token
                    response.addCookie(cookie);
                }
            }
        }
    }

    //注册激活
    @GetMapping("user/verify")
    @Anoymous
    public ResponseData userVerify( String uuid, String username){
        UserVerifyResponse userVerifyResponse = loginService.userVerify(uuid,username);
        if (!SysRetCodeConstants.SUCCESS.getCode().equals(userVerifyResponse.getCode())) {
            return new ResponseUtil<>().setErrorMsg(userVerifyResponse.getMsg());
        }
        return new ResponseUtil<>().setData(userVerifyResponse);
    }
}
